<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>bitdn首页</title>
</head>
<body>
    <div id="app">
        <h2>bitdn首页</h2>
        <div v-if="user.nickname">欢迎你，{{user.nickname}} <a href="javascript:void(0)" @click="logout()">注销</a> <a href="personal.html">个人博客管理</a></div>
        <div v-else><a href="login.html">登录</a>/<a href="register.html">注册</a></div>
        <ul>
            <li v-for="article in articles">
                <a href="javascript:void(0)" @click="toDetail(article.id);">{{article.title}}</a>
            </li>
        </ul>
    </div>
    <script type="application/javascript" src="vue.js"></script>
    <script type="application/javascript" src="axios.js"></script>
    <script>
        let app = new Vue({
            el: "#app",
            data: {
                user: {},
                articles: [],
                // articles: [{
                //     id: 1,
                //     title: "a"
                // }]
            },
            methods: {
                toDetail: function (id) {
                    //localStorage是客户端本地保存数据的方式，页面跳转时比较有用
                    localStorage.setItem('aid', id);
                    window.location.href = "detail.html";
                },
                logout: function () {
                    //注销功能：发送ajax请求，服务端删除session中保存的user
                    axios.get("api/user/logout")
                        .then(function (resp) {
                            let body = resp.data;
                            if(body.ok){
                                app.user = {};
                            }else{
                                alert(body.message)
                            }
                        })
                }
            },
            //初始化方法：页面加载后就执行
            created: function () {
                //发送首页初始化ajax请求，获取登录用户及文章列表
                axios.get("api/article/init")
                    .then(function (resp) {
                        // console.log(resp)
                        //后端返回的json数据
                        let body = resp.data;
                        if(body.ok){
                            //如果||前的值为空，就赋值为||后的值
                            app.user = body.data.user || {};
                            app.articles = body.data.articleList || [];
                        }else{
                            alert(body.message)
                        }
                    })
            }
        });
    </script>
</body>
</html>